package com;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.StaticLog;
import com.c.rabbit_mq.impl.Iot212MsgExe;
import com.c.rabbit_mq.impl.IotMsgPush;
import com.modular.iot.bo.IotData;
import com.tool.ToolHex;
import com.tool.rabbit.RabbitMsgBO;
import ntd.block.server.bo.ComServerInBo;
import ntd.block.server.bo.ComServerMsgBo;
import ntd.block.server.impl.ComServerTcp;
import ntd.block.server.listen.ComAbsServerListen;
import ntd.protocol.Ntd212Parse;
import ntd.protocol.bo.Ntd212BO;
import ntd.util.frame.action.iot.bo.SmartEmissionAgreementBo;
import ntd.util.frame.action.iot.cache.SmartEmissionAgreementCache;
import ntd.util.modular.data.util.handle.tool.Tool212;
import ntd.util.modular.things.entity.Device;
import ntd.util.str.ToolCutMsg;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: liuwenju
 * @date: 2023/8/3 17:18
 * @version: 1.0
 */
public class LJ212Listen {

    private static final Map<String, ToolCutMsg> toolCutMsgMap = new HashMap<>();

    public static void main(String[] args) {
        ComServerTcp comServerTcp = new ComServerTcp();

        comServerTcp.addListen(new ComAbsServerListen() {
            @Override
            public ComServerMsgBo onMsg(ComServerMsgBo comServerMsgBo) {
                String key = comServerMsgBo.getKey();
                List<String> strings = new ArrayList<>();
                if (ToolHex.isHexNumber(comServerMsgBo.getMsg())) {
                    strings.addAll(cutMsg(key + "-hex", HexUtil.decodeHexStr(comServerMsgBo.getMsg())));
                } else {
                    strings.addAll(cutMsg(key, comServerMsgBo.getMsg()));
                }
                for (String string : strings) {
                    handleMsg(comServerMsgBo, string);
                }
                return null;
            }

            @Override
            public void onClose(ComServerMsgBo comServerMsgBo) {

            }
        });

        comServerTcp.init(gen_in_bo());

    }

    /**
     * 切割数据
     *
     * @param key
     * @param msg
     * @return
     */
    public static List<String> cutMsg(String key, String msg) {
        ToolCutMsg toolCutMsg = toolCutMsgMap.get(key);
        if (ObjectUtil.isNull(toolCutMsg)) {
            toolCutMsgMap.put(key, toolCutMsg = ToolCutMsg.me(Tool212.getCutMsg()));
        }
        return toolCutMsg.parseDeep(msg);
    }

    /**
     * 执行数据
     * @param comServerMsgBo
     * @param msg
     */
    public static void handleMsg(ComServerMsgBo comServerMsgBo, String msg) {
        if (StrUtil.isBlank(msg)) {
            return;
        }
        try {
            // 适配16进制
            if (HexUtil.isHexNumber(msg)) {
                msg = HexUtil.decodeHexStr(msg, CharsetUtil.CHARSET_UTF_8);
            }

            Ntd212BO ntd212BO = Ntd212Parse.parse(msg).getNtd212BO();

            StaticLog.info("LJ收到212报文[{}]", msg);
            if (StrUtil.isBlank(ntd212BO.getMN())) {
                StaticLog.error("LJ报文缺少mn编号[{}]", msg);
                return;
            }
            // 设备数据同步 - 没有的话自动新增
            Device device = ToolOpt.OPT_T_DEVICE.initDevice(ntd212BO.getMN(), comServerMsgBo.getIp());

            // 绑定mn对应通道关系
            Tool212.bindMn(ntd212BO.getMN(), comServerMsgBo.getKey());

            // 推送到 rabbitmq
            Iot212MsgExe.push(msg);

            // 同步到Mqtt
            Iot212MsgExe.pushMqtt(ntd212BO.getMN(), msg);

        } catch (Exception e) {
            StaticLog.error(e, "[212][采集端][数据解析][{}]失败...", msg);
        }
    }

    public static void handle9802(Ntd212BO ntd212BO, Device device) {
        Map<String, String> cpData = ntd212BO.getCPData();
        String exeRtn = cpData.get("ExeRtn");
        SmartEmissionAgreementBo smartEmissionAgreementBo = SmartEmissionAgreementBo.init(exeRtn);
        // 设备断电后，执行应急操作
        if (smartEmissionAgreementBo.isPowerOff()) {
            Tool212.pushSt32Emergency(ntd212BO.getMN(), "断电应急");
        }
        SmartEmissionAgreementCache.update(device.getCode(), "blowdown_valve", smartEmissionAgreementBo.isValve());
        SmartEmissionAgreementCache.update(device.getCode(), "emergency_valve", smartEmissionAgreementBo.isValve2());
    }

    public static void handle212Data(Ntd212BO ntd212BO) {
        IotData iotData = IotData.transform212(ntd212BO);
        iotData.setTenantId("40289f5a7e94f892017e951800160000");
        // 查找并保存设备数据信息
        ToolOpt.OPT_T_DATA.saveIotData(iotData);

        if (Tool212.DATA_CNS.contains(ntd212BO.getCN())) {
            IotMsgPush.push(new RabbitMsgBO(ntd212BO.getMN(), Tool212.generatorResMsg(ntd212BO)));
        }
    }


    private static ComServerInBo gen_in_bo() {
        ComServerInBo comServerInBo = new ComServerInBo();
        comServerInBo.setPort(37041);
        return comServerInBo;
    }
}
